package com.bawei.search.vm;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bawei.search.R;

import java.util.ArrayList;

/**
 * Author: Jason Zhang
 * Date: 2025/2/6
 * Desc: 自定义流式布局，实现搜索页面关键词展示换行效果
 */
public class FlowBoxLayout extends ViewGroup {


    private HistoryItemOnClick mHistoryItemOnClick;


    public FlowBoxLayout(Context context) {
        super(context);
    }

    public FlowBoxLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FlowBoxLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public FlowBoxLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    /**
     * 设置点击事件
     * @param itemOnClick
     */
    public void setItemOnClick(HistoryItemOnClick itemOnClick) {
        mHistoryItemOnClick = itemOnClick;
    }

    /**
     * 添加历史记录
     */
    public void addHistoryText(ArrayList<String> list) {
        if (list == null || list.size() == 0) return;
        TextView itemView;
        MarginLayoutParams layoutParams;
        for (String itemText : list) {
            itemView = new TextView(getContext());
            itemView.setText(itemText);
            itemView.setTextColor(Color.BLACK);
            itemView.setTextSize(16f);
            //设置外边距
            layoutParams = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(10, 5, 10, 5);
            itemView.setLayoutParams(layoutParams);
            //设置内边距
            itemView.setPadding(10, 5, 10, 5);
            //设置背景
            itemView.setBackgroundResource(R.drawable.shape_keyword_bg);
            //添加子组件到父布局中
            itemView.setOnClickListener(v -> mHistoryItemOnClick.onItemClick(v, itemText));
            addView(itemView);
        }

        //请求重新布局，重新执行onMeasure和onLayout方法
        requestLayout();
    }

    /**
     * 组件以及子组件大小的测量
     * widthMeasureSpec 为2位的Int值，前4位代表测量模式(EXACTLY，AT_MOST，UNSPECIFIED)，后30位代码组件大小
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //1.测量子组件的大小（必须）
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        //2.重新设置父布局大小（必须）
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
    }

    /**
     * 用来摆放子组件
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //基本思路：获取所有子组件->计算子组件大小->判断是否换行->设置上下左右边到父布局的上边和左边的距离->调用子组件的layout方法
        int count = getChildCount();
        //定义组件左上角的坐标
        int top = 0, left = 0;
        //定义行宽和行高
        int lineWidth = 0, lineHeight = 0;
        View childView;
        MarginLayoutParams layoutParams;
        int childWidth = 0, childHeight = 0;
        for (int i = 0; i < count; i++) {
            childView = getChildAt(i);
            layoutParams = (MarginLayoutParams) childView.getLayoutParams();
            childWidth = childView.getMeasuredWidth() + layoutParams.leftMargin + layoutParams.rightMargin;
            childHeight = childView.getMeasuredHeight() + layoutParams.topMargin + layoutParams.bottomMargin;
            //判断是否换行
            if (lineWidth + childWidth > getMeasuredWidth()) { //换行
                lineWidth = childWidth;
                lineHeight = childHeight;
                top += childHeight;
                left = 0;
            } else {
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            }
            //计算4个边
            int cl = left + layoutParams.leftMargin;
            int ct = top + layoutParams.topMargin;
            int cr = cl + childView.getMeasuredWidth();
            int cb = ct + childView.getMeasuredHeight();
            //摆放子组件
            childView.layout(cl, ct, cr, cb);
            //更新left
            left += childWidth;
        }

    }

    /**
     * 以下三个方法用于获取子组件的外边距
     **/
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateLayoutParams(LayoutParams p) {
        return new MarginLayoutParams(p);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    }

    /**
     * 定义点击事件接口类
     */
    public interface HistoryItemOnClick{
        void onItemClick(View view, String historyText);
    }
}
